The ZonedDateTime
is an immutable representation of a date-time with a time-zone, introduced in Java 8. This class stores all date and
time fields, to a precision of nanoseconds, and a time zone, with a zone offset used to handle ambiguous local date times.
Date truncation to a specific time unit means setting the values up to the specific time unit to zero while keeping the values of the larger time
units unchanged.
The ZonedDateTime
class provides a truncatedTo
method that allows truncating the date in a significantly faster way than
the DateUtils
class from Commons Lang.
Note that this rule is automatically disabled when the project’s sonar.java.source
is lower than 8
.
Noncompliant code example
public Date trunc(Date date) {
return DateUtils.truncate(date, Calendar.SECOND); // Noncompliant
}
Compliant solution
public Date trunc(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
ZonedDateTime truncatedZonedDateTime = zonedDateTime.truncatedTo(ChronoUnit.SECONDS);
Instant truncatedInstant = truncatedZonedDateTime.toInstant();
return Date.from(truncatedInstant);
}